<template>
  <el-form
    ref="ruleForm"
    :model="ruleForm"
    status-icon
    :rules="rules"
    label-width="150px"
    class="demo-ruleForm"
  >
    <el-form-item label="旧密码" prop="oldPassword">
      <el-input
        v-model="ruleForm.oldPassword"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input
        v-model="ruleForm.newPassword"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item label="再次输入新密码" prop="checkPassword">
      <el-input
        v-model="ruleForm.checkPassword"
        type="password"
        autocomplete="off"
      />
    </el-form-item>
    <el-form-item>
      <el-alert
        :closable="false"
        title="提示：密码长度大于等于6位，小于等于12位，必需包含数字和字母。"
        type="info"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
export default {
  data() {
    const validatePass = (rule, value, callback) => {
      if (value) {
        if (this.ruleForm.checkPassword !== '') {
          this.$refs.ruleForm.validateField('checkPassword')
        }
        const pwdRegEn = /[A-Za-z].*[0-9]|[0-9].*[A-Za-z]/
        if (!pwdRegEn.test(value)) {
          callback(new Error('密码必需包含数字和字母'))
          return
        }
      }
      callback()
    }
    const validatePass2 = (rule, value, callback) => {
      if (value && value !== this.ruleForm.newPassword) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      ruleForm: {},
      rules: {
        oldPassword: [
          { required: true, message: '请输入旧密码', trigger: 'blur' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, message: '密码不能少于6位', trigger: 'blur' },
          { max: 12, message: '密码不能大于12位', trigger: ['change', 'blur'] },
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (!valid) {
          return
        }
   
        this.$store.dispatch('user/onUpdatePwd', this.ruleForm)
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>
